﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using TdxHq.Common.Extend;
using TdxHq.Connect;
using TdxHq.Invoker;

namespace TdxHq.Looper
{
    public class HqLooper
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(HqLooper));
        public bool Stop = false;
        public Queue Queue = new Queue();
        public TdxConnection TdxConnection;
        public List<Stkinfo> StockList;
        public static readonly int RequestSize = 50;

        public OnDisconnect Listener { set; get; }

        public HqLooper(TdxConnection tdxConnection,List<Stkinfo> stockList)
        {
            this.TdxConnection = tdxConnection;
            var list = stockList;
            this.StockList = list;

            var stkinfos = list;
            var connection = TdxConnection;
        }

        public void Run()
        {
            while (!Stop)
            {
                
                var limit = StockList.Count / 50 + 1;
                foreach (var list in StockList.Partition(limit))
                {
                    List<QuoteRt> quoteRts = Quote.Quotes(TdxConnection, list);
                    
                    if (null != quoteRts && quoteRts.Count != 0)
                    {
                        QueueLooper.Instance.AddData(quoteRts);
                        
                    }
                    else if (TdxConnection.ConnectTime > 10)
                    {
                        Stop = true;
                        _log.Error("HqLooper stop connection name = " + TdxConnection.ConnectionName + "\t" + "ip = " +
                                   TdxConnection.Ip + "\nstock list = " + StockList.List2String());
                        Listener?.Invoke(TdxConnection);
                        return;
                    }

                    Thread.Sleep(20);
                }                
            }
        }
        
        public delegate void OnDisconnect(TdxConnection connection);
    }
}